/*
 * @Author: your name
 * @Date: 2020-09-13 08:40:42
 * @LastEditTime: 2020-10-04 16:49:21
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \woniutaofang\lib\pages\home\home_page.dart
 */
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:woniutaofang/components/houselistpage/house_widget.dart';
import 'package:woniutaofang/components/ui/loader.dart';
import 'package:woniutaofang/components/ui/shimmer_view.dart';
import 'package:woniutaofang/enum/enum.dart';
import 'package:woniutaofang/model/Home/getHomeBuildings.dart';
import 'package:woniutaofang/pages/home/widgets/search_widget.dart';
import 'package:woniutaofang/pages/home/widgets/slivergrid_widget.dart';
import 'package:woniutaofang/pages/home/widgets/swiper_widget.dart';
import 'package:woniutaofang/service/api_service.dart';
import 'package:woniutaofang/utils/state_layout.dart';

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  bool get wantKeepAlive => true;
  List swiperDataList = [
    'https://wx2.sinaimg.cn/mw690/66fa6be4gy1fzd1sif9tuj218g0p143d.jpg',
    'https://wx2.sinaimg.cn/mw690/66fa6be4gy1fzd1sif9tuj218g0p143d.jpg',
    'https://wx2.sinaimg.cn/mw690/66fa6be4gy1fzd1sif9tuj218g0p143d.jpg'
  ];
  List list = [];
  LoaderState state = LoaderState.Loading;

  var _scrollController = ScrollController();
  var _showBackTop = false;

  // void _setGoodsCount(int count) {
  //   // Provider.of<GoodsPageProvider>(context, listen: false).setGoodsCount(count);
  //   /// 与上方等价，provider 4.1.0添加的拓展方法
  //   context.read<GoodsPageProvider>().setGoodsCount(count);
  // }
  void _getHomeBuildings() async {
    GetHomeBuildingsModel data = await ApiService.getHomeBuildings();
    if (data != null) {
      setState(() {
        list = data.data;
      });
      state = LoaderState.Succeed;
    } else {
      state = LoaderState.NoAction;
    }
  }

  Future _onRefresh() async {
    await Future.delayed(const Duration(seconds: 2), () {
      setState(() {
        _page = 1;
        // _list = List.generate(widget.index == 0 ? 3 : 10, (i) =>
        //     GoodsItemEntity(icon: _imgList[i % 6], title: '八月十五中秋月饼礼盒', type: i % 3));
      });
      // _setGoodsCount(_list.length);
    });
  }

  Future _loadMore() async {
    await Future.delayed(const Duration(seconds: 2), () {
      setState(() {
        // _list.addAll(List.generate(
        //     10,
        //     (i) => GoodsItemEntity(
        //         icon: _imgList[i % 6], title: '八月十五中秋月饼礼盒', type: i % 3)));
        _page++;
      });
      // _setGoodsCount(_list.length);
    });
  }

  @override
  void initState() {
    super.initState();
    // 对 scrollController 进行监听
    _scrollController.addListener(() {
      // _scrollController.position.pixels 获取当前滚动部件滚动的距离
      // 当滚动距离大于 800 之后，显示回到顶部按钮
      setState(() => _showBackTop = _scrollController.position.pixels >= 800);
    });
    _getHomeBuildings();
    //Item数量
    _maxPage = 1;
    // var time = Timer.periodic(Duration(milliseconds: 1500), //间隔时间
    //     (_) {
    //   //回调函数,参数是定时器对象
    //   //...
    //   _getHomeBuildings();
    //   //停止定时器,不取消会一直执行
    // });
    // Future.delayed(
    //   Duration(seconds: 10),
    //   () {
    //     // time.cancel();
    //     _getHomeBuildings();
    //   },
    // );
  }

  EasyRefreshController _controller = EasyRefreshController();
  int _page = 1;
  int _maxPage;
  StateType _stateType = StateType.loading;
  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: true);
    super.build(context);
    return Scaffold(
        appBar: AppBar(
          title: Text('首页'),
          backgroundColor: Colors.red,
        ),
        body: LoaderContainer(
          loadingView: ShimmerView(),
          contentView:
              // DeerListView(
              //     itemCount: list.length,
              //     stateType: _stateType,
              //     onRefresh: _onRefresh,
              //     loadMore: _loadMore,
              //     hasMore: _page < _maxPage,
              //     itemBuilder: (_, index) {
              //       return ListView(
              //         shrinkWrap: true,
              //         physics: NeverScrollableScrollPhysics(),
              //         children: <Widget>[
              //           SearchWidget(),
              //           SwiperWidget(swiperDataList: swiperDataList),
              //           SliverGridWidget(),
              //           HouseWidget(houselist: list)
              //         ],
              //       );
              //     }),
              EasyRefresh(
            controller: _controller,
            onLoad: () async {
              await Future.delayed(
                Duration(seconds: 2),
                () {
                  if (mounted) {
                    setState(
                      () {
                        // list..add({})..add({})..add({});
                      },
                    );
                    // _controller.finishLoad(noMore: list.length >= 10);
                  }
                },
              );
            },
            onRefresh: () async {
              await Future.delayed(Duration(seconds: 2), () {
                if (mounted) {
                  setState(
                    () {
                      // list = ['', '', ''];
                    },
                  );
                  // _controller.finishLoad(noMore: false, success: true);
                }
              });
            },
            child: ListView(
              controller: _scrollController,
              children: <Widget>[
                SearchWidget(),
                SwiperWidget(swiperDataList: swiperDataList),
                SliverGridWidget(),
                HouseWidget(houselist: list)
              ],
            ),
          ),
          loaderState: state,
        ),
        floatingActionButton: _showBackTop // 当需要显示的时候展示按钮，不需要的时候隐藏，设置 null
            ? FloatingActionButton(
                backgroundColor: Colors.red,
                mini: true,
                onPressed: () {
                  // scrollController 通过 animateTo 方法滚动到某个具体高度
                  // duration 表示动画的时长，curve 表示动画的运行方式，flutter 在 Curves 提供了许多方式
                  _scrollController.animateTo(0.0,
                      duration: Duration(milliseconds: 300),
                      curve: Curves.decelerate);
                },
                child: Icon(
                  Icons.vertical_align_top,
                  color: Colors.white,
                ),
              )
            : null);
  }
}
